from prg.command_info import CommandInfo
from prg.entity.arg_entity import ArgBase
from prg.common.common_base import CommonBase
from prg.common.object_message import MessageBase
import socket
import random


class RunUdpBeat(MessageBase):
    def __init__(self, name, udp_port):
        super().__init__(name="udp_svr_" + name)
        self.sign = None
        self.addr_name = name
        self.address = None
        self.verify_code = None
        self.udp_bind = ("", udp_port)
        self.random_num = random.randint(1, 99999)

    def bind_udp(self, address, verify_code, sign):
        self.sign = sign
        self.address = address
        self.verify_code = verify_code
        self.start()

    def entry(self):
        print("udp -> server start %s" % str(self.address))
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server_socket:
            server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            server_socket.bind(self.udp_bind)
            server_socket.connect(self.address)
            # while self.exec:
            print("udp -> server beat %s" % str(self.random_num))
            self.random_num += 1
            arg = ArgBase()
            arg.sign = self.sign
            arg.arg_dict = dict()
            arg.arg_dict["beat"] = self.random_num
            arg.arg_dict["verification"] = self.verify_code
            arg_str = CommonBase.aes_encryption_json(key=self.sign, entity=arg)
            cmd_item = CommandInfo(socket_item=server_socket, name=self.addr_name, command="beat", arg=arg_str)
            cmd_item.send()
            # time.sleep(30)
